#include <iostream>
#include <dirent.h> //文件系统相关库
#include "linktree.h"
#include <sys/stat.h>


std::string double2(double num)
{
 return   std::to_string((1.0*(int)(num*100)/100));
}



std::string Transform(size_t size)
{
    if (size<1024)
    {
        return std::string(std::to_string(size))+"B";
    }
    else if(size<1024*1024)
    {
        return std::string(std::to_string((1.0*size)/1024))+"kB";
    }
    else if (size<1024*1024*1024)
    {
         return std::string(std::to_string((1.0*size)/(1024*1024)))+"MB";
    }
    else  if (size>1024*1024*1024)
    {
        return std::string(std::to_string((1.0*size)/(1024*1024*1024)))+"GB";
    }
    return "";
}
// 扫描文件夹
void ExplorDir(const std::string &path, TreeNode *node)
{
    DIR *dir = opendir((path + "/").c_str()); // 打开文件夹
    if (dir == nullptr)
    {
        std::cout << "文件夹路径有错误！：" << path << std::endl;
        return;
    }
    // 读取文件目录下的文件列表

    dirent *e = nullptr;
    while ((e = readdir(dir)) != nullptr)
    {
        if (std::string(e->d_name) == "." || std::string(e->d_name) == "..")
        {
            continue;
        }
        TreeNode *child = new TreeNode(e->d_name);
        child->Connect(node);
        if (e->d_type == DT_DIR)
        {
            ExplorDir(path + "/" + std::string(e->d_name), child);
        }
        else
        {

        struct stat s;
        stat((path+"/"+std::string(e->d_name)).c_str(),&s);
        child->SetDate(std::string(e->d_name)+"  size:"+Transform(s.st_size));

        }
    }
    // 关闭
    closedir(dir);
}

// argc代表命令行参数数量
// argv代表命令行参数数值数组

int main(int argc, char *argv[])
{
    std::string path;
    if (argc < 2)
    {
        path = "./";
    }
    else
    {
        path = argv[1];
    }

    LinkTree tree(path);
    ExplorDir(path, tree.GetRoot());
     tree.show();
    // DARRAY::DynamicArray a = tree.FindByElement("1");
    // for (int i = 0; i < a.Size(); i++)
    // {
    // std::cout << tree.GetNodePath((TreeNode*)a[i]) << std::endl;
    // }
    
    // std::cout<<"文件大小："<<s.st_size<<std::endl;
   
   
   
   return 0;
}